package Commands;

import domain.Controller;

import domain.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CmdDoLogin extends Command
{
  String nextJspUrl = 
    "userStory3.jsp"; 
  CommandFactory comFac;
  Controller controller;

  public void init(CommandFactory comFac, Controller c)
    throws ServletException 
  {
    this.comFac = comFac;
    this.controller = c;
  }

  public void execute(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException 
  {
    HttpSession session = req.getSession();
    String username = req.getParameter("username");
    int sid = -1;
    try 
    {
      sid = Integer.parseInt(username);
    } catch (Exception ex) 
    {
      nextJspUrl = "elevLogin.jsp";
    }
    if(sid != -1)
    {
      try
      {
        Student s = controller.getStudent(sid);
        if(s.getId() == sid)
        {
          nextJspUrl = session.getAttribute("refpage").toString()+ ".jsp";
          session.setAttribute("authed","elev");
          session.setAttribute("authid",sid);
          session.setAttribute("status",null);
        }
      }
      catch (Exception ex)
      {
        nextJspUrl = "elevLogin.jsp";
      }
    }
    else
      nextJspUrl = "elevLogin.jsp";
      
    
  }
  
  public String getNextJspUrl()
  {
    return nextJspUrl;
  }
}